// addressBook.js - 添加真实数据结构，但不改变页面展示字段
const util = require('../../utils/utils.js');

Page({
  data: {
    currentDate: '',
    stocks: []
  },

  onShow() {
    this.setData({
      currentDate: util.formatDate(new Date())
    });
    this.loadStockData();
    // 每5秒刷新一次
    this.updateInterval = setInterval(() => {
      this.loadStockData();
    }, 5000);
  },

  onLoad() {
    this.loadStockData();
  },

  onUnload() {
    if (this.updateInterval) {
      clearInterval(this.updateInterval);
    }
  },

  loadStockData() {
    let _this = this;
    const stockCodes = [
      'sh600340', // 华夏幸福
      'sh600589', // 大位科技
      'sh601318', // 中国平安
      'sh600519', // 贵州茅台
      'sz300750', // 宁德时代
      'sh600036', // 招商银行
      'sh601166', // 兴业银行
      'sh688316',
      'sh688025',
      'sh688163',
      'sh688700',
      'sh688062',
      'sh600650',
      'sh600570',
      'sh688115'
    ];
    const stockCodesStr = stockCodes.join(',');

    wx.request({
      url: `https://hq.sinajs.cn/list=${stockCodesStr}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          const data = res.data.split('\n');
          const stocks = [];
          for (let i = 0; i < data.length; i++) {
            const line = data[i].trim();
            if (line) {
              const nameMatch = line.match(/\"(.+)\"/);
              const name = nameMatch ? nameMatch[1].split(',')[0] : '';
              const stockInfo = line.split(',');
              if (stockInfo.length >= 34) {
                const code = stockInfo[0].split('=')[0].replace('var hq_str_', '');
                const currentPrice = parseFloat(stockInfo[3]);
                const yesterdayClose = parseFloat(stockInfo[2]);
                const todayOpen = parseFloat(stockInfo[1]);
                const tradedAmount = parseFloat(stockInfo[9]) / 10000;
                const changeRate = ((currentPrice - yesterdayClose) / yesterdayClose * 100).toFixed(2);
                const riseSpeed = todayOpen === 0 ? 0 : ((currentPrice - todayOpen) / todayOpen * 100).toFixed(2);

                // 页面原字段（不变）
                const stock = {
                  code: code,
                  name: name,
                  price: currentPrice,
                  change: changeRate + '%',
                  isRise: currentPrice >= yesterdayClose,

                  // 新增真实字段，供首页排行榜使用
                  currentPrice,
                  yesterdayClose,
                  todayOpen,
                  tradedAmount,
                  changeRate,
                  speed: parseFloat(riseSpeed)
                };
                stocks.push(stock);
              }
            }
          }

   // ✅ 添加模拟股票（含成交量）
        const mockStocks = [
          {
            code: 'mock001', name: '模拟用的（不要点）', price: 12.34, change: '2.45%', isRise: true,
            currentPrice: 12.34, yesterdayClose: 12.04, todayOpen: 11.90, tradedAmount: 32800,
            changeRate: 2.45, speed: 3.70
          }
        ];

          const allStocks = [...stocks, ...mockStocks];
          _this.setData({ stocks: allStocks });

          // ✅ 写入首页榜单使用的全局数据
          getApp().globalData.allStocks = allStocks;
          console.log('✅ 已写入 globalData.allStocks:', allStocks);
        }
      },
      fail: (err) => {
        console.error('Request failed:', err);
      }
    });
  },

  goToStockDetail(e) {
    const stockCode = e.currentTarget.dataset.code;
    const stockName = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: `/pages/stock/stock?name=${encodeURIComponent(stockName)}&code=${stockCode}`
    });
  }
});
